<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的激励页面 - 儿童打卡系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
            min-height: 100vh;
        }
        .card-bounce {
            transition: transform 0.3s ease;
        }
        .card-bounce:hover {
            transform: translateY(-5px);
        }
        .progress-bar {
            transition: width 0.5s ease-in-out;
        }
        .celebration {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000;
            display: none;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="bg-white bg-opacity-90 shadow-lg">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16 items-center">
                <div class="flex items-center">
                    <i class="fas fa-star text-2xl mr-3 text-yellow-500"></i>
                    <h1 class="text-xl font-bold text-gray-800">我的激励小天地</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <div class="bg-yellow-100 px-3 py-1 rounded-full">
                        <i class="fas fa-coins text-yellow-600 mr-1"></i>
                        <span class="font-bold text-yellow-800" id="pointsDisplay">0</span>
                    </div>
                    <a href="/logout" class="text-gray-600 hover:text-gray-800">
                        <i class="fas fa-sign-out-alt text-xl"></i>
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- 今日任务 -->
        <div class="bg-white rounded-2xl p-6 mb-8 card-shadow">
            <h2 class="text-2xl font-bold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-calendar-day mr-3 text-blue-500"></i>
                今日任务清单
            </h2>
            <div id="todayTasks" class="space-y-4">
                <!-- 动态加载任务 -->
            </div>
        </div>

        <!-- 徽章和奖励 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- 我的徽章 -->
            <div class="bg-white rounded-2xl p-6 card-shadow">
                <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                    <i class="fas fa-medal mr-3 text-yellow-500"></i>
                    我的徽章
                </h3>
                <div id="myBadges" class="flex flex-wrap gap-3">
                    <!-- 动态加载徽章 -->
                </div>
                
                <!-- 下一个徽章进度 -->
                <div id="nextBadge" class="mt-6">
                    <!-- 动态加载下一个徽章 -->
                </div>
            </div>

            <!-- 可兑换奖励 -->
            <div class="bg-white rounded-2xl p-6 card-shadow">
                <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                    <i class="fas fa-gift mr-3 text-purple-500"></i>
                    可兑换奖励
                </h3>
                <div id="availableRewards" class="space-y-3">
                    <!-- 动态加载奖励 -->
                </div>
            </div>
        </div>

        <!-- 成就动画 -->
        <div id="celebration" class="celebration">
            <div class="bg-white rounded-2xl p-8 text-center shadow-2xl">
                <i class="fas fa-trophy text-6xl text-yellow-500 mb-4"></i>
                <h3 class="text-2xl font-bold text-gray-800 mb-2">太棒了！</h3>
                <p class="text-gray-600" id="celebrationText">你获得了新的成就！</p>
                <button onclick="closeCelebration()" class="mt-4 bg-yellow-500 text-white px-6 py-2 rounded-lg hover:bg-yellow-600">
                    继续加油！
                </button>
            </div>
        </div>
    </div>

    <script>
        let childData = {};

        async function loadChildData() {
            try {
                const response = await fetch('/api/child/data');
                childData = await response.json();
                
                // 更新积分显示
                document.getElementById('pointsDisplay').textContent = childData.points;
                
                // 更新今日任务
                updateTodayTasks(childData.today_tasks);
                
                // 更新徽章
                updateBadges(childData.badges);
                
                // 更新下一个徽章进度
                updateNextBadge(childData.next_badge);
                
                // 更新可兑换奖励
                updateRewards(childData.available_rewards);
                
            } catch (error) {
                console.error('加载数据失败:', error);
            }
        }

        function updateTodayTasks(tasks) {
            const container = document.getElementById('todayTasks');
            container.innerHTML = '';
            
            tasks.forEach(task => {
                const div = document.createElement('div');
                div.className = 'flex items-center justify-between p-4 bg-gray-50 rounded-lg card-bounce';
                div.innerHTML = `
                    <div class="flex items-center">
                        <div class="w-12 h-12 rounded-full flex items-center justify-center ${
                            task.completed ? 'bg-green-100' : 'bg-gray-100'
                        }">
                            <i class="fas fa-${task.completed ? 'check' : 'clock'} text-${
                                task.completed ? 'green' : 'gray'
                            }-500"></i>
                        </div>
                        <div class="ml-4">
                            <h4 class="font-semibold text-gray-800">${task.name}</h4>
                            <p class="text-sm text-gray-600">+${task.points} 积分</p>
                        </div>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" ${task.completed ? 'checked' : ''} 
                               onchange="toggleTask(${task.id}, this.checked)"
                               class="sr-only peer">
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                `;
                container.appendChild(div);
            });
        }

        function updateBadges(badges) {
            const container = document.getElementById('myBadges');
            container.innerHTML = '';
            
            if (badges.length === 0) {
                container.innerHTML = '<p class="text-gray-500 text-sm">还没有获得徽章，继续努力！</p>';
                return;
            }
            
            badges.forEach(badgeName => {
                const span = document.createElement('span');
                span.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-100 text-yellow-800';
                span.innerHTML = `
                    <i class="fas fa-medal mr-1"></i>
                    ${badgeName}
                `;
                container.appendChild(span);
            });
        }

        function updateNextBadge(nextBadge) {
            const container = document.getElementById('nextBadge');
            if (!nextBadge) {
                container.innerHTML = '<p class="text-gray-500 text-sm">已获得所有徽章！</p>';
                return;
            }
            
            const progress = Math.min((childData.points / nextBadge.required_points) * 100, 100);
            
            container.innerHTML = `
                <h4 class="font-semibold text-gray-800 mb-2">下一个目标：${nextBadge.name}</h4>
                <div class="bg-gray-200 rounded-full h-3 mb-2">
                    <div class="bg-yellow-500 h-3 rounded-full progress-bar" style="width: ${progress}%"></div>
                </div>
                <p class="text-sm text-gray-600">${childData.points}/${nextBadge.required_points} 积分</p>
                <p class="text-xs text-gray-500 mt-1">${nextBadge.description}</p>
            `;
        }

        function updateRewards(rewards) {
            const container = document.getElementById('availableRewards');
            container.innerHTML = '';
            
            rewards.forEach(reward => {
                const canAfford = childData.points >= reward.points_cost;
                const div = document.createElement('div');
                div.className = `p-4 rounded-lg border-2 ${
                    canAfford ? 'border-green-200 bg-green-50' : 'border-gray-200 bg-gray-50'
                } card-bounce`;
                div.innerHTML = `
                    <div class="flex justify-between items-center">
                        <div>
                            <h4 class="font-semibold text-gray-800">${reward.name}</h4>
                            <p class="text-sm text-gray-600">${reward.points_cost} 积分</p>
                        </div>
                        <button onclick="redeemReward(${reward.id})" 
                                class="px-4 py-2 rounded-lg font-medium ${
                                    canAfford ? 'bg-green-500 text-white hover:bg-green-600' : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                                }" ${!canAfford ? 'disabled' : ''}>
                            ${canAfford ? '兑换' : '积分不足'}
                        </button>
                    </div>
                `;
                container.appendChild(div);
            });
        }

        async function toggleTask(taskId, completed) {
            try {
                const response = await fetch(`/api/child/task/${taskId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ completed })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 更新积分显示
                    document.getElementById('pointsDisplay').textContent = data.points;
                    
                    // 重新加载数据
                    await loadChildData();
                    
                    // 显示庆祝动画
                    if (completed) {
                        showCelebration(`获得积分 +${event.target.closest('.card-bounce').querySelector('.text-sm').textContent.match(/\\d+/)[0]}！`);
                    }
                }
            } catch (error) {
                console.error('更新任务失败:', error);
            }
        }

        async function redeemReward(rewardId) {
            if (!confirm('确定要兑换这个奖励吗？')) return;
            
            try {
                const response = await fetch('/api/child/redeem', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ reward_id: rewardId })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('pointsDisplay').textContent = data.points;
                    await loadChildData();
                    showCelebration('奖励兑换成功！');
                } else if (data.error === '积分不足') {
                    alert('积分不足，无法兑换！');
                }
            } catch (error) {
                console.error('兑换奖励失败:', error);
            }
        }

        function showCelebration(text) {
            document.getElementById('celebrationText').textContent = text;
            document.getElementById('celebration').style.display = 'block';
        }

        function closeCelebration() {
            document.getElementById('celebration').style.display = 'none';
        }

        // 页面加载时获取数据
        loadChildData();
        
        // 每30秒刷新一次数据
        setInterval(loadChildData, 30000);
    </script>
</body>
</html>
